import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/king/king_list_entity.dart';
import 'package:sports_new/entity/king/king_scroll_entity.dart';
import 'package:sports_new/server/api/king_api.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';

import '../../entity/king/king_entity.dart';
import '../../server/api/other_api.dart';

class KingLogic extends GetxController with GetTickerProviderStateMixin{
  late final TabController tabController;
  int dateIndex = 0;
  String? rule;
  List<DateTime>? dayList;
  Map<int,String> button = {};
  List<String> buttonRoute = [Routes.match];
  KingListEntity? data;
  List<KingScrollEntity>? scorllInfo;
  List<List<KingEntity>?> matchList = List.generate(7, (index) => null);
  int total = 0;

  @override
  void onReady() async{
    Utils.onEvent('king');
    getScrollBar();
    await getData();
    tabController = TabController(
        length: dayList?.length ?? 0,
        vsync: this,
        initialIndex: dayList?.hasValue == false?0:dayList
        !.indexWhere((element) => element.day == DateTime.now().day));
    tabController.addListener(() {
      dateIndex = tabController.index;
      update();
      getData(index: tabController.index);
    });
    super.onReady();
  }

  Future getRule() async{
    var tips = await OtherApi.getAppList("app_res_tips");
    try {
      rule = tips
          ?.firstWhere((element) => element.button == "activity_king_tip")
          .content;
    }catch(e){
      log("no king_rule");
    }
  }
  
  Future getData({int? index}) async{
    if(index == null) dayList = [];
    data = await KingApi.getKingList(
        index == null
          ? "" : dayList?[tabController.index].formatedString('yyyy-MM-dd'));
    if (index == null) {
      dayList?.addAll(data?.dayList?.map((e) => DateTime.parse(e.day ?? "")) ?? []);
      dateIndex = dayList?.hasValue == false?0:dayList!.indexWhere((element) => element.day == DateTime.now().day);
      matchList[dateIndex] = data?.matchList ?? [];
      button = {
        if(data?.dayRank == 1)
        3:"日榜",
        if(data?.weekRank == 1)
        1:"周榜",
        if(data?.monthRank == 1)
        2:"月榜",
        8:"我的预测"
      };
    } else {
      matchList[index] = data?.matchList ?? [];
    }
    total = matchList[index ?? dateIndex]?.length ?? 0;
    update();
  }

  Future getScrollBar() async{
    scorllInfo = await KingApi.getScrollInfo();
    update();
  }
}